#include "async_server.h"
#include "globals.h"
#include <iostream>

namespace async_server {

using namespace std;

AsyncSession::AsyncSession(boost::asio::io_service &io_service)
	:TcpSession(io_service)
{

};

AsyncSession::~AsyncSession()
{
	//cout << "~AsyncSession" << endl;
};

AsyncSession::pointer AsyncSession::clone()
{
	return pointer(new AsyncSession(socket_.get_io_service()));
};

void AsyncSession::process_read()
{
	istream ss(&response_);
	std::string tmp, tmp2;
	while (ss >> tmp)
	{
		if (tmp == "ping")
		{
			shared_ptr<PING_INFO> ping_info = shared_ptr<PING_INFO>(new PING_INFO);
			ping_info->session = shared_from_this();
			getline(ss, tmp2);
			stringstream ss2(tmp2);
			ss2 >> tmp;
			ping_info->message = tmp;
			eventDriver.emitEvent("ping", ping_info);
		}
		else if (tmp == "pong")
		{
			shared_ptr<PING_INFO> pong_info = shared_ptr<PING_INFO>(new PING_INFO);
			pong_info->session = shared_from_this();
			getline(ss, tmp2);
			stringstream ss2(tmp2);
			ss2 >> tmp;
			pong_info->message = tmp;
			eventDriver.emitEvent("pong", pong_info);
		}
		else
		{
			shared_ptr<UNDEFINED_MSG_INFO> undef_info = shared_ptr<UNDEFINED_MSG_INFO>(new UNDEFINED_MSG_INFO);
			undef_info->session = shared_from_this();
			stringstream ss3;
			ss3 << tmp << " ";
			getline(ss, tmp2);
			stringstream ss2(tmp2);
			while(ss2 >> tmp)
			{
				ss3 << " "<< tmp;
			}
			undef_info->message = ss3.str();
			eventDriver.emitEvent("error", undef_info);
		}
	}
	
};

}; // namespace async_server

